<template>
  <a-button type="link" @click="openAdvancedModal">高级查询</a-button>
  <AdvancedTypeName
    @register="registerTypeName"
    :configs="currentQueryType.queryConfig"
    :tableKey="tableKey"
    @success="handleSuccess"
  />
  <BasicModal :title="getTitle" width="50%" :height="500" @register="register">
    <div class="query-sider">
      <div class="query-sider-content">
        <ul>
          <li
            v-for="(item, index) in queryTypes"
            :key="index"
            @click="handleChangeQuery(item)"
          >
            <div
              class="type-name"
              :class="item.id === currentQueryType.id ? 'active' : ''"
            >
              <div class="check-icon">
                <Icon
                  icon="ant-design:check-outlined"
                  v-if="item.isDefault === 'Y'"
                  :color="item.id === currentQueryType.id ? '#fff' : ''"
                />
              </div>
              <span>{{ item.queryName }}</span>
            </div>

            <a-button
              type="link"
              :style="{
                fontSize: '12px',
              }"
              v-if="item.id !== '0'"
              @click="handleSetDefault(item)"
              >{{ item.isDefault === 'Y' ? '取消' : '选为默认' }}</a-button
            >
          </li>
        </ul>
        <div class="collapse-icon-container">
          <Icon icon="ic:baseline-arrow-back-ios-new" />
        </div>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-between">
        <div class="left-buttons">
          <a-button type="primary" @click="handleNewQuery">新方案</a-button>
          <a-button type="primary" @click="showNameModal">保存方案</a-button>
        </div>
        <div class="right-buttons">
          <a-button type="primary" @click="handleSearch">查询</a-button>
        </div>
      </div>
    </template>
    <div>
      <div class="query-contaier">
        <draggable
          :list="allQueryFields"
          :sort="false"
          :clone="handleClone"
          :itemKey="(item) => item.dataIndex"
          :group="{
            name: 'advanced',
            pull: 'clone',
            put: false,
          }"
          filter=".undraggable"
          class="select-fields"
        >
          <template #item="{ element }">
            <div
              class="field"
              :class="
                currentQueryType.queryConfig.find(
                  (d) => d.field === element.field
                )
                  ? 'undraggable'
                  : ''
              "
            >
              {{ element.label }}<span class="arrow">></span>
            </div>
          </template>
        </draggable>
        <div class="query-conditions">
          <Empty
            v-if="!currentQueryType.queryConfig.length"
            style="position: absolute; width: 100%"
          />
          <draggable
            class="fields-list"
            v-model="currentQueryType.queryConfig"
            :sort="true"
            :group="{ name: 'advanced' }"
            :itemKey="(item) => item.field"
            @add="handleAdd"
          >
            <template #item="{ element }">
              <AdvancedQueryComponent
                :schema="element"
                @deleteField="handleDeleteField"
                :setFormModel="setFormModel"
                :setQuerySchema="(k, v) => setQuerySchema(k, v)"
              />
            </template>
          </draggable>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script setup lang="ts">
import { ref, onMounted, unref, toRaw } from 'vue';
import draggable from 'vuedraggable';
import { BasicModal, useModal } from '@/components/Modal';
import { BasicColumn, FormSchema } from '@/components/Table';
import { Empty } from 'ant-design-vue';
import { transQueryFields } from '@/components/Table/src/utils/queryTrans';
import AdvancedQueryComponent from './AdvancedQueryComponent.vue';
import { edit, setDefault, list } from '@/api/sys/sysUserQueryManage';
import { useMessage } from '@/hooks/web/useMessage';
import Icon from '@/components/Icon/Icon.vue';
import AdvancedTypeName from './AdvancedTypeName.vue';
import { computed } from 'vue';
import { QueryOptEnum } from '@/enums/QueryOptEnum';

const { createMessage } = useMessage();
const emit = defineEmits(['advanced-search', 'set-default']);
interface QueryField extends FormSchema {
  queryOption: string;
  queryOptions: { label: string; value: string }[];
}
type QueryType = {
  id?: string;
  queryName: string;
  queryConfig: FormSchema[];
  tableKey: string;
  isDefault: string;
};
const props = defineProps({
  tableKey: {
    type: String as PropType<String>,
  },
  searchFormSchema: {
    type: Array as PropType<FormSchema[]>,
  },
  columns: {
    type: Array as PropType<BasicColumn[]>,
    default: () => [],
  },
  value: {
    type: Array as PropType<QueryField[]>,
    default: () => [],
  },
});
const queryTypes = ref<QueryType[]>([]);
const allQueryFields = unref(props.columns)
  .filter((c) => c.querySchema)
  .map((c) => {
    return {
      labelWidth: 120,
      ...c.querySchema,
    };
  });

const sysDefaultQuery = {
  id: '0',
  queryConfig: allQueryFields.filter((a) => a?.defaultSearch),
  queryName: '默认方案',
  isDefault: '',
  tableKey: props.tableKey as string,
};
let currentQueryType = ref(sysDefaultQuery);
const reloadList = async () => {
  const userData = (await list()) as any;
  queryTypes.value = [
    sysDefaultQuery,
    ...userData.map((u) => {
      return {
        ...u,
        queryConfig: JSON.parse(u.queryConfig),
      };
    }),
  ];
  const defaultData = userData.find((d) => d.isDefault === 'Y');
  if (defaultData) {
    emit('set-default', JSON.parse(defaultData.queryConfig));
  }
};
onMounted(async () => {
  await reloadList();
  // currentQueryType.value = queryTypes.value[0];
});
const defaultFormModel = {};

const [register, { openModal }] = useModal();
const openAdvancedModal = () => {
  openModal(true);
};

queryTypes.value.push(toRaw(currentQueryType.value));
const setFormModel = (key: string, value: any) => {
  // ;
  defaultFormModel[key] = value;
};
const setQuerySchema = (v, a) => {
  let querySchema = currentQueryType.value.queryConfig.find(
    (item) => item.field === a.field
  );
  querySchema.queryOption = v;
  if (a.component.indexOf('Date') > -1 || a.component === 'RangePicker') {
    if (v === QueryOptEnum.DATE_BWT) {
      querySchema.component = 'RangePicker';
    }
    if (v === QueryOptEnum.EQ) {
      querySchema.component = 'DatePicker';
    }
  }
};

const handleAdd = () => {};

const handleClone = (e) => {
  console.log({ ...toRaw(e), labelWidth: 120 });
  return {
    ...toRaw(e),
    labelWidth: 120,
  };
};
// 字段配置混入到数据中
const mixinSchemaToData = () => {
  return transQueryFields(defaultFormModel, currentQueryType.value.queryConfig);
};
const handleSearch = () => {
  emit('advanced-search', mixinSchemaToData());
};
const [registerTypeName, { openModal: openTypeNameModal }] = useModal();
const showNameModal = async () => {
  // ;
  if (currentQueryType.value.id && currentQueryType.value.id !== '0') {
    const { id, tableKey, queryName, queryConfig } = currentQueryType.value;
    await edit({
      id,
      tableKey,
      queryConfig: JSON.stringify(queryConfig),
      queryName,
    });
    reloadList();
    createMessage.success('保存成功');
    return;
  }
  openTypeNameModal();
};
const handleNewQuery = () => {
  currentQueryType.value = {
    id: '',
    tableKey: props.tableKey as string,
    queryConfig: [],
    isDefault: '',
    queryName: '',
  };
};
const handleSuccess = () => {
  reloadList();
};
const getTitle = computed(() => {
  return '高级查询：' + currentQueryType.value.queryName;
});
const handleDeleteField = (field: string) => {
  // 从defaultConditions中删除元素
  currentQueryType.value.queryConfig.splice(
    currentQueryType.value.queryConfig.findIndex((d) => d.field === field),
    1
  );
};
const handleChangeQuery = (item) => {
  currentQueryType.value = { ...item };
  console.log(currentQueryType.value, item, queryTypes, 'cccccccc');
};
const handleSetDefault = async (item) => {
  await setDefault(item.id);
  reloadList();
  emit(
    'set-default',
    queryTypes.value.find((i) => i.id === item.id)?.queryConfig
  );
};
</script>
<style lang="less" scoped>
.type-name {
  width: 100px;
  display: flex;
  align-items: center;
}
.query-sider {
  position: absolute;
  right: -10px;
  top: 0;
  z-index: 1;
  width: 10px;
  height: 100%;
  background: #fff;
  border: 1px solid #e5e7eb;
  transition: all 0.3s;
  .active {
    background: @primary-color;
    color: #fff;
  }
  .query-sider-content {
    padding: 10px;
    position: relative;
    ul > li {
      height: 32px;
      display: flex;
      padding-left: 5px;
      font-size: 12px;
      justify-content: space-between;
    }
    .check-icon {
      display: flex;
      width: 20px;
      align-items: center;
    }
    .type-name {
      width: 100px;
      overflow: hidden;
    }
    .collapse-icon-container {
      position: absolute;
      left: -15px;
      top: 100px;
      width: 15px;
      height: 40px;
      background: rgb(215, 214, 214);
      border: 1px solid rgb(165, 164, 164);
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.query-sider:hover {
  width: 200px;
  cursor: pointer;
}

.query-contaier {
  padding: 10px;
  display: flex;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  .select-fields {
    width: 150px;
    height: 100%;
    border-right: 1px solid black;
    overflow-y: auto;
    cursor: s-resize;
    .undraggable {
      color: gray;
      cursor: not-allowed;
    }
  }

  .field {
    padding: 2px 8px;
    margin-bottom: 4px;
    cursor: move;
  }
  .field:hover {
    background-color: @primary-color;
    color: #ffffff;
  }
  .field:hover .arrow {
    display: block;
  }
  .arrow {
    display: none;
    float: right;
  }
  .query-conditions {
    flex: 1;
    padding: 0 0 0 20px;
    overflow: hidden;
    position: relative;
    .fields-list {
      height: 100%;
      width: 100%;
      padding-left: 20px;
      padding-right: 20px;
      position: absolute;
      top: 0;
      left: 0;
      overflow-y: auto;
      .query-type {
        width: 120px;
      }
      :deep(.ant-form-item) {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
